<?php

namespace stlswm\WeChatMp\User;

use stlswm\WeChatMp\CurlHttp;
use stlswm\WeChatMp\MiniProgram;
use stlswm\WeChatMp\Response;

/**
 * Class PhoneNumber
 * 获取手机号
 * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
 */
class PhoneNumber
{
    use CurlHttp;

    /**
     * @var MiniProgram
     */
    protected MiniProgram $miniProgram;

    /**
     * Auth constructor.
     * @param  MiniProgram  $miniProgram
     */
    public function __construct(MiniProgram $miniProgram)
    {
        $this->miniProgram = $miniProgram;
    }

    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）
     * @param  string  $code
     * @param  string  $openid
     * @return Response
     */
    public function getPhoneNumber(string $code, string $openid = ''): Response
    {
        $accessToken = $this->miniProgram->getAccessToken();
        $url = MiniProgram::$baseUri.'/wxa/business/getuserphonenumber?access_token='.$accessToken;
        $body = [
            'code' => $code,
        ];
        if ($openid) {
            $body['openid'] = $openid;
        }
        return self::postJson($url, $body);
    }
}